<template>
  <div class="order-pay">
    <div class="pay-container">
      <el-card class="pay-card">
        <template #header>
          <div class="card-header">
            <span>订单支付</span>
          </div>
        </template>

        <!-- 订单信息 -->
        <div class="order-info">
          <div class="info-item">
            <span class="label">订单编号：</span>
            <span class="value">{{ order.orderSn }}</span>
          </div>
          <div class="info-item amount">
            <span class="label">支付金额：</span>
            <span class="value price">¥{{ order.payAmount }}</span>
          </div>
        </div>

        <!-- 支付方式 -->
        <div class="pay-methods">
          <div class="section-title">选择支付方式</div>
          <div class="method-list">
            <div
              v-for="method in payMethods"
              :key="method.type"
              class="method-item"
              :class="{ active: selectedMethod === method.type }"
              @click="selectPayMethod(method.type)"
            >
              <img :src="getPayMethodIcon(method.type)" :alt="method.name" class="method-icon">
              <span class="method-name">{{ method.name }}</span>
            </div>
          </div>
        </div>

        <!-- 支付按钮 -->
        <div class="pay-actions">
          <el-button type="primary" size="large" @click="handlePay" :loading="paying">
            立即支付
          </el-button>
          <el-button link type="info" @click="handlePayLater">稍后支付</el-button>
        </div>
      </el-card>
    </div>

    <!-- 支付结果弹窗 -->
    <el-dialog
      v-model="showPayResult"
      :title="paySuccess ? '支付成功' : '支付失败'"
      width="30%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      class="pay-result-dialog"
    >
      <div class="pay-result">
        <el-icon :size="64" :color="paySuccess ? '#67c23a' : '#f56c6c'">
          <component :is="paySuccess ? 'CircleCheckFilled' : 'CircleCloseFilled'" />
        </el-icon>
        <p>{{ paySuccess ? '订单支付成功' : '订单支付失败，请重试' }}</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="goToOrderList" v-if="paySuccess">查看订单</el-button>
          <el-button type="primary" @click="retryPay" v-else>重新支付</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOrder, payOrder, cancelOrder } from '@/api/order'
import { CircleCheckFilled, CircleCloseFilled } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

// 订单数据
const order = ref({})
const paying = ref(false)
const showPayResult = ref(false)
const paySuccess = ref(false)
const orderCheckTimer = ref(null)

// 支付方式
const payMethods = [
  {
    type: 1,
    name: '支付宝支付',
    icon: 'alipay'
  },
  {
    type: 2,
    name: '微信支付',
    icon: 'wechat'
  }
]
const selectedMethod = ref(1)

// 获取支付方式图标
const getPayMethodIcon = (type) => {
  const iconName = type === 1 ? 'alipay' : 'wechat'
  return new URL(`@/assets/images/${iconName}.svg`, import.meta.url).href
}

// 选择支付方式
const selectPayMethod = (type) => {
  selectedMethod.value = type
}

// 获取订单信息
const getOrderInfo = async () => {
  try {
    const orderSn = route.params.orderSn
    if (!orderSn) {
      ElMessage.error('订单编号不能为空')
      router.push('/order/list')
      return
    }
    const res = await getOrder(orderSn)
    if (res.code === 200) {
      order.value = res.data
      // 检查订单状态，如果已支付则直接显示成功
      if (order.value.status === 1) {
        showPaySuccess()
      }
    } else {
      ElMessage.error(res.msg || '获取订单信息失败')
      router.push('/order/list')
    }
  } catch (error) {
    console.error('获取订单信息失败:', error)
    ElMessage.error('获取订单信息失败')
    router.push('/order/list')
  }
}

// 处理支付
const handlePay = async () => {
  try {
    if (paying.value) return
    paying.value = true
    
    const orderSn = order.value.orderSn
    if (!orderSn) {
      ElMessage.error('订单编号不能为空')
      paying.value = false
      return
    }

    const res = await payOrder(orderSn, selectedMethod.value)
    if (res.code === 200) {
      startOrderCheck()
    } else {
      showPayFail(res.msg)
    }
  } catch (error) {
    console.error('支付失败:', error)
    showPayFail(error.message)
  } finally {
    paying.value = false
  }
}

// 显示支付成功
const showPaySuccess = () => {
  paySuccess.value = true
  showPayResult.value = true
  stopOrderCheck()
  // 跳转到支付结果页面
  router.push({
    path: '/order/result',
    query: {
      status: 'success',
      orderSn: order.value.orderSn
    }
  })
}

// 显示支付失败
const showPayFail = (msg) => {
  paySuccess.value = false
  showPayResult.value = true
  ElMessage.error(msg || '支付失败，请重试')
}

// 取消订单
const handleCancel = async () => {
  if (!order.value.orderSn) {
    ElMessage.error('订单信息不完整')
    return
  }

  try {
    await ElMessageBox.confirm('确定要取消订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await cancelOrder(order.value.orderSn)
    if (res.code === 200) {
      ElMessage.success('订单已取消')
      router.push('/order/list')
    } else {
      throw new Error(res.msg || '取消订单失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error(error.message || '取消订单失败')
    }
  }
}

// 开始检查订单状态
const startOrderCheck = () => {
  stopOrderCheck()
  orderCheckTimer.value = setInterval(async () => {
    try {
      const orderSn = order.value.orderSn
      const res = await getOrder(orderSn)
      if (res.code === 200 && res.data.status === 1) {
        showPaySuccess()
      }
    } catch (error) {
      console.error('检查订单状态失败:', error)
    }
  }, 3000)
}

// 停止检查订单状态
const stopOrderCheck = () => {
  if (orderCheckTimer.value) {
    clearInterval(orderCheckTimer.value)
    orderCheckTimer.value = null
  }
}

// 监听路由参数变化
watch(() => route.params.orderSn, (newOrderSn) => {
  console.log('路由参数变化:', newOrderSn)
  if (newOrderSn) {
    getOrderInfo()
  }
}, { immediate: true })

// 重试支付
const retryPay = () => {
  showPayResult.value = false
  handlePay()
}

// 查看订单列表
const goToOrderList = () => {
  router.push('/order/list')
}

// 处理稍后支付
const handlePayLater = () => {
  ElMessage.info('您可以在订单列表中继续支付')
  router.push('/order/list')
}

onMounted(() => {
  console.log('支付页面组件挂载')
  const orderSn = route.params.orderSn
  if (orderSn) {
    getOrderInfo()
  }
})

onUnmounted(() => {
  stopOrderCheck()
})
</script>

<style lang="scss" scoped>
.order-pay {
  padding: 40px;
  min-height: 100vh;
  background: linear-gradient(135deg, #f6f8fb 0%, #f1f4f9 100%);
  display: flex;
  justify-content: center;
  align-items: flex-start;

  .pay-container {
    width: 100%;
    max-width: 800px;
  }

  .pay-card {
    border-radius: 24px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
    border: none;
    overflow: hidden;
    background: #fff;

    :deep(.el-card__header) {
      padding: 24px 32px;
      border-bottom: 1px solid #eef0f5;
      background: linear-gradient(145deg, #ffffff, #f8f9fa);
      
      .card-header {
        display: flex;
        align-items: center;
        
        span {
          font-size: 24px;
          font-weight: 600;
          color: #2c3e50;
          position: relative;
          padding-left: 16px;
          
          &::before {
            content: '';
            position: absolute;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            width: 4px;
            height: 24px;
            background: linear-gradient(45deg, #8B4513, #D2691E);
            border-radius: 2px;
          }
        }
      }
    }

    :deep(.el-card__body) {
      padding: 32px;
    }
  }

  .order-info {
    padding: 32px;
    background: linear-gradient(145deg, #ffffff, #f8f9fa);
    border-radius: 16px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
    margin-bottom: 32px;

    .info-item {
      display: flex;
      align-items: center;
      margin-bottom: 16px;
      
      &:last-child {
        margin-bottom: 0;
      }

      &.amount {
        margin-top: 24px;
        padding-top: 24px;
        border-top: 1px solid #eef0f5;

        .value.price {
          font-size: 32px;
          font-weight: 700;
          background: linear-gradient(45deg, #8B4513, #D2691E);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
        }
      }

      .label {
        width: 100px;
        color: #7f8c8d;
        font-size: 15px;
      }

      .value {
        flex: 1;
        color: #2c3e50;
        font-size: 16px;
        font-weight: 500;
      }
    }
  }

  .pay-methods {
    margin-bottom: 32px;

    .section-title {
      font-size: 20px;
      font-weight: 600;
      color: #2c3e50;
      margin-bottom: 24px;
      position: relative;
      padding-left: 16px;
      
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 4px;
        height: 20px;
        background: linear-gradient(45deg, #8B4513, #D2691E);
        border-radius: 2px;
      }
    }

    .method-list {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 24px;
      padding: 0 32px;

      .method-item {
        display: flex;
        align-items: center;
        padding: 24px;
        background: linear-gradient(145deg, #ffffff, #f8f9fa);
        border-radius: 16px;
        cursor: pointer;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
        border: 2px solid transparent;
        
        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
        }
        
        &.active {
          background: linear-gradient(145deg, #fff5e6, #fff8f0);
          border-color: #8B4513;
        }

        .method-icon {
          width: 40px;
          height: 40px;
          margin-right: 16px;
          transition: transform 0.3s ease;
        }

        .method-name {
          font-size: 16px;
          font-weight: 600;
          color: #2c3e50;
        }

        &:hover .method-icon {
          transform: scale(1.1);
        }
      }
    }
  }

  .pay-actions {
    text-align: center;
    padding: 32px 0 16px;

    :deep(.el-button) {
      padding: 16px 48px;
      font-size: 18px;
      font-weight: 600;
      border-radius: 12px;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      margin: 0 12px;
      
      &--primary {
        background: linear-gradient(45deg, #8B4513, #D2691E);
        border: none;
        
        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 8px 24px rgba(139, 69, 19, 0.25);
        }
        
        &:active {
          transform: translateY(0);
        }

        &.is-loading {
          &::before {
            background-color: rgba(255, 255, 255, 0.35);
          }
        }
      }
      
      &--text {
        color: #7f8c8d;
        
        &:hover {
          color: #8B4513;
        }
      }
    }
  }
}

.pay-result {
  text-align: center;
  padding: 40px 0;

  .el-icon {
    margin-bottom: 24px;
  }

  p {
    font-size: 18px;
    color: #2c3e50;
  }
}

:deep(.el-dialog) {
  border-radius: 24px;
  overflow: hidden;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
  
  .el-dialog__header {
    margin: 0;
    padding: 24px 32px;
    border-bottom: 1px solid #eef0f5;
    background: linear-gradient(145deg, #ffffff, #f8f9fa);
    
    .el-dialog__title {
      font-size: 20px;
      font-weight: 600;
      color: #2c3e50;
    }
  }
  
  .el-dialog__body {
    padding: 32px;
  }
  
  .el-dialog__footer {
    padding: 24px 32px;
    border-top: 1px solid #eef0f5;
    background: linear-gradient(145deg, #ffffff, #f8f9fa);
  }
}

// 响应式布局优化
@media screen and (max-width: 768px) {
  .order-pay {
    padding: 20px;

    .pay-card {
      :deep(.el-card__header) {
        padding: 20px;
        
        .card-header span {
          font-size: 20px;
        }
      }

      :deep(.el-card__body) {
        padding: 20px;
      }
    }

    .order-info {
      padding: 20px;
      margin-bottom: 24px;

      .info-item {
        &.amount {
          margin-top: 20px;
          padding-top: 20px;

          .value.price {
            font-size: 28px;
          }
        }
      }
    }

    .pay-methods {
      margin-bottom: 24px;

      .section-title {
        font-size: 18px;
        margin-bottom: 20px;
      }

      .method-list {
        grid-template-columns: 1fr;
        padding: 0;

        .method-item {
          padding: 16px;
        }
      }
    }

    .pay-actions {
      padding: 24px 0 12px;

      :deep(.el-button) {
        width: calc(100% - 32px);
        margin: 8px 16px;
        padding: 12px 24px;
        font-size: 16px;
      }
    }
  }

  :deep(.el-dialog) {
    width: 90% !important;
    margin: 0 auto;
    
    .el-dialog__body {
      padding: 20px;
    }
  }
}
</style>
